package com.yricky.indesk.a.activity

import android.os.Bundle
import android.text.format.DateFormat
import android.view.KeyEvent
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import com.yricky.indesk.ui.compose.page.MainActivityPage
import com.yricky.indesk.utils.CfgEvent
import com.yricky.indesk.utils.TimeEvent
import com.yricky.indesk.utils.cfgChannel
import com.yricky.indesk.utils.minuteTimerChannel
import com.yricky.indesk.viewmodel.MainActivityViewModel
import me.yricky.event.Audience

class MainActivity : ComponentActivity() {
    private val viewModel:MainActivityViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        cfgChannel.register(cfgAudience)
        minuteTimerChannel.register(timeAudience)
        setContent { MainActivityPage(viewModel = viewModel) }
        viewModel.onAction(MainActivityViewModel.Action.QueryConfig)
    }

    override fun onDestroy() {
        super.onDestroy()
        cfgChannel.unregister(cfgAudience)
        minuteTimerChannel.unregister(timeAudience)
    }

    override fun onStart() {
        super.onStart()
        cfgAudience.attach { onCfgEvent(it) }
        timeAudience.attach { onTime() }
        onTime()
    }

    override fun onStop() {
        super.onStop()
        cfgAudience.detach()
        timeAudience.detach()
    }

    /**
     * Activity 只在其存活时对部分设置变化消息感兴趣
     */
    private val cfgAudience:Audience<CfgEvent> = Audience.Newest()
    private fun onCfgEvent(event:CfgEvent){
        when(event){
            is CfgEvent.DCfgChanged ->{
                viewModel.onAction(MainActivityViewModel.Action.QueryConfig)
            }
            else->{}
        }
    }

    private val timeAudience:Audience<TimeEvent> = Audience.Simple()
    private fun onTime(){
        viewModel.onAction(MainActivityViewModel.Action.SetBottomText(
            DateFormat.format("yyyy-MM-dd,hh:mm:ss",System.currentTimeMillis()).toString()
        ))
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        return super.onKeyUp(keyCode, event)
    }

    override fun onBackPressed() {
        //桌面主界面返回键不能退出了
    }
}


